<!-- src/components/DetailDialog.vue -->
<template>
  <el-dialog
    v-model="isVisible"
    title="表详情"
    width="50%"
    :close-on-click-modal="false"
    :show-close="false"
    class="meter-detail-dialog"
    :top="'5px'"
  >
    <div class="detail-content">
      <!-- 基本信息和监控信息合并为一个描述列表 -->
      <el-descriptions :column="2" border class="info-section">
        <el-descriptions-item label="表ID">
          <div class="value-cell">{{ meterId }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="监控ID">
          <div class="value-cell">{{ monitorId }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="别名">
          <div class="value-cell">{{ alias }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="AI识别结果">
          <div class="value-cell">
            {{ removeQuotesFromAiRes ? removeQuotesFromAiRes : '未识别' }} {{ unit }}
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 图片信息 -->
      <div class="section" v-if="shouldShowImage">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="监控图片">
            <div class="image-wrapper">
              <template v-if="imgRes === 'No upload'">
                <div class="no-image">
                  <el-icon><Picture /></el-icon>
                  <span>图片未上传</span>
                </div>
              </template>
              <img v-else :src="imgRes" alt="监控图片" class="monitor-image"/>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 监控更新记录 -->
      <div class="section" v-if="hasMonitorInfo">
        <h3>监控更新记录</h3>
        <el-table :data="monitorRecords" style="width: 100%" border stripe>
          <el-table-column prop="mac" label="MAC地址" align="center" min-width="120"/>
          <el-table-column prop="updateTime" label="更新时间" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.updateTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="fetchHistoryData">查看历史信息</el-button>
        <el-button type="primary" @click="openCreateMonitorDialog">添加监控</el-button>
        <el-button 
          type="success" 
          @click="handleLabel" 
          :disabled="isLabeled || refreshing"
          :loading="refreshing"
        >
          {{ refreshing ? '刷新中' : '刷新' }}
        </el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加监控弹窗 -->
  <el-dialog
    v-model="createMonitorVisible"
    title="添加监控"
    width="30%"
    :close-on-click-modal="false"
    class="create-monitor-dialog"
    append-to-body
  >
    <div class="monitor-form">
      <el-form :model="monitorForm" label-width="100px">
        <el-form-item label="监控ID">
          <el-input 
            v-model="monitorForm.monitorId" 
            placeholder="请输入监控ID"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="createMonitorVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="createMonitors" 
          :loading="creating"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 历史数据弹窗 -->
  <el-dialog
    v-model="isHistoryDialogVisible"
    title="历史数据"
    width="60%"
    @close="handleClose"
  >
    <el-table :data="paginatedHistoryData" style="width: 100%">
      <el-table-column
        prop="time"
        label="时间"
        width="180"
      />
      <el-table-column
        prop="content"
        label="内容"
      />
    </el-table>
    <template #footer>
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="Object.entries(historyData).length"
        layout="total, prev, pager, next"
      />
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { createMonitor,refreshDetails } from '../api/meter.js';
import { Picture } from '@element-plus/icons-vue'
import axios from 'axios'; // 引入 axios

export default {
  components: {
    Picture
  },
  props: {
    visible: Boolean,
    meterId: [String, Number],
    alias: String,
    unit: String,
    AiRes: String,
    imgRes: String,
    type: String,
    monitorId: String
  },
  data() {
    return {
      createMonitorVisible: false,
      creating: false,
      refreshing: false,
      isHistoryDialogVisible: false, // 控制历史数据弹窗的显示
      historyData: {}, // 存储历史数据，初始化为对象
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条目数
      monitorForm: {
        monitorId: ''
      },
      isLabeled: false // 添加 isLabeled 属性
    }
  },
  computed: {
    // 使用方法来去除 AiRes 中的双引号
    removeQuotesFromAiRes() {
      return this.removeQuotes(this.AiRes);
    },
    isVisible: {
      get() {
        return this.visible
      },
      set(value) {
        this.$emit('update:visible', value)
      }
    },
    parsedAiRes() {
      try {
        const aiRes = JSON.parse(this.AiRes);
        return aiRes || {};
      } catch {
        return {};
      }
    },
    parsedImgLabel() {
      try {
        return JSON.parse(this.imgLabel)
      } catch {
        return null
      }
    },
    hasMonitorInfo() {
      return this.monitorInfo && Object.keys(this.monitorInfo).length > 0;
    },
    monitorRecords() {
      if (!this.hasMonitorInfo) return [];

      const records = [];
      // 遍历监控信息对象
      Object.entries(this.monitorInfo).forEach(([imgName, macInfo]) => {
        Object.entries(macInfo).forEach(([mac, updateTime]) => {
          records.push({
            mac,
            updateTime
          });
        });
      });
      return records;
    },
    shouldShowImage() {
      // 只有当imgRes存在且不为undefined时才显示图片区域
      return this.imgRes !== undefined;
    },
    paginatedHistoryData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return Object.entries(this.historyData).slice(start, end).map(([time, content]) => ({ time, content }));
    },
    totalPages() {
      return Math.ceil(Object.entries(this.historyData).length / this.pageSize);
    }
  },
  methods: {
    removeQuotes(str) {
      // 使用正则表达式替换双引号为空字符串
      return str.replace(/"/g, '');
    },
    //刷新
    async handleLabel() {
      if (this.refreshing) return;
      
      this.refreshing = true;
      try {
        const response = await refreshDetails(this.monitorId);
        console.log('返回的信息:', response.data);
        if (response && response.data) {
          this.$emit('update:AiRes', response.data.aiValue);
          this.$emit('update:imgRes', response.data.image_path);
          this.$message.success('刷新成功');
        } else {
          this.$message.warning('暂无新数据');
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('刷新失败');
      } finally {
        setTimeout(() => {
          this.refreshing = false;
        }, 500); // 至少显示500ms的加载状态
      }
    },
    close() {
      this.isVisible = false
    },
    openCreateMonitorDialog() {
      this.createMonitorVisible = true;
      this.monitorForm.monitorId = ''; // 清空表单
    },
    //创建监控
    async createMonitors() {
      if (!this.monitorForm.monitorId) {
        this.$message.error('请输入监控ID');
        return;
      }

      this.creating = true;
      try {
        const response = await createMonitor(
            this.meterId,
            this.monitorForm.monitorId,
            this.type
        );
        if(response.includes('失败')){
          this.$message.error("当前监控ID不支持");
        }else {
          this.$message.success('创建成功');
          this.createMonitorVisible = false; // 关闭添加监控弹窗
          this.isVisible = false; // 关闭详情弹窗
        }
        
        // 触发父组件刷新数据
        this.$emit('refresh');
      } catch (error) {
        this.$message.error('创建失败');
        console.error(error);
      } finally {
        this.creating = false;
      }
    },
    async fetchHistoryData() {
      console.log('Fetching history data...');
      try {
        const response = await axios.post('http://47.96.91.185:4399/getlogs', {
          device_id: this.monitorId,
          data: this.type
        });

        console.log('Response:', response);
        if (response.status === 200) {
          const result = {};
          const lines = response.data.split('\n');

          lines.forEach(line => {
            const parts = line.trim().split(' ');
            if (parts.length >= 3) { // 确保有足够的部分
              const time = parts[0] + ' ' + parts[1];
              const jsonStr = parts[2];
              result[time] = jsonStr;
            } else {
              console.warn('数据格式不正确:', line); // 添加警告以调试
            }
          });
          this.historyData = result; // 设置历史数据
          this.isHistoryDialogVisible = true; // 显示历史数据弹窗
          console.log('History dialog should be visible now.');
        } else {
          this.$message.warning('获取历史数据失败');
        }
      } catch (error) {
        console.error('请求历史数据失败:', error);
        this.$message.error('请求历史数据失败');
      }
    },
    // 关闭历史数据弹窗
    handleClose() {
      this.isHistoryDialogVisible = false; // 隐藏历史数据弹窗
    },
    formatDate(dateString) {
      try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch {
        return dateString;
      }
    },
    handlePageChange(page) {
      this.currentPage = page;
    }
  }
}
</script>
<style scoped>
.meter-detail-dialog :deep(.el-dialog) {
  margin-top: 5px !important;
}

.meter-detail-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px;
  border-bottom: 1px solid #dcdfe6;
}

.meter-detail-dialog :deep(.el-dialog__headerbtn) {
  display: none;
}

.meter-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.detail-content {
  padding: 0;
}

.section {
  margin-top: 20px;
}

.section h3 {
  margin-bottom: 15px;
  color: var(--el-text-color-primary);
  font-size: 16px;
  font-weight: 500;
}

.info-section {
  margin-bottom: 20px;
}

/* 描述列表样式 */
:deep(.el-descriptions__cell) {
  padding: 12px 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
  justify-content: flex-end;
  background-color: var(--el-fill-color-light);
  font-size: 14px;
  color: #606266;
  padding: 12px 20px;
}

:deep(.el-descriptions__content) {
  font-size: 14px;
  color: var(--el-text-color-primary);
  padding: 0;
}

/* 值单元格样式 */
.value-cell {
  min-height: 40px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  word-break: break-all;
  line-height: 1.4;
}

/* 确保所有描述项的内容区域高度一致 */
:deep(.el-descriptions__body) {
  width: 100%;
}

:deep(.el-descriptions__table) {
  width: 100%;
  table-layout: fixed;
}

:deep(.el-descriptions__cell.is-bordered-content) {
  width: calc(50% - 120px);
}

/* 图片容器样式 */
.image-wrapper {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  overflow: hidden;
  padding: 10px;
}

.monitor-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 表格样式 */
:deep(.el-table th) {
  background-color: var(--el-fill-color-light);
  font-size: 14px;
  color: #606266;
}

:deep(.el-table td) {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

/* 底部按钮样式 */
.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #dcdfe6;
}

.dialog-footer .el-button {
  margin-left: 12px;
  min-width: 90px; /* 确保按钮宽度一致 */
}

/* 添加刷新按钮的过渡效果 */
.dialog-footer .el-button {
  transition: all 0.3s;
}

/* 添加监控弹窗样式 */
.create-monitor-dialog {
  border-radius: 8px;
}

.create-monitor-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.create-monitor-dialog :deep(.el-dialog__body) {
  padding: 24px 20px;
}

.monitor-form {
  width: 100%;
}

.monitor-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-regular);
}

.monitor-form :deep(.el-input) {
  width: 100%;
}

/* 确保弹窗在详情弹窗之上 */
.create-monitor-dialog :deep(.el-dialog) {
  z-index: 3000;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  height: 100%;
}

.no-image .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.no-image span {
  font-size: 14px;
}
</style>